/*
 * timer.c
 *
 *  Created on: 2013. 10. 16.
 *      Author: jphong
 */

#include	"np.h"

struct timeval *timer = NULL;		/* active timer */

/* Start a timer */
void start_timer(unsigned int msec )
{
	static struct timeval interval, now, timeout;		/* timeout in time of day */

	if ( msec <= 0 ) {
		timer = NULL;			// ignore
	}
	if ( gettimeofday( &now, NULL ) < 0 )
		error( 1, errno, "timeout: gettimeofday failure" );
	interval.tv_sec = msec / 1000;
	interval.tv_usec = ( msec % 1000) * 1000;
	timeradd( &now, &interval, &timeout );
	timer = &timeout;
	debug("Timer started\n");
	return;
}

/* cancel a timer */
void stop_timer()
{
	timer = NULL;
	debug("Timer stopped\n");
	return;
}

int timer( int maxp1, fd_set *re, fd_set *we, fd_set *ee )
{
 struct timeval now;
 struct timeval tv;
 struct timeval *tvp;

 if ( active )   // if timer is running
 {
  if ( gettimeofday( &now, NULL ) < 0 )
   error( 1, errno, "timer: gettimeofday failure" );
  if ( !timercmp(&now, active, <) ) // timeout elapsed
   return 0;
  tv.tv_sec = active->tv_sec - now.tv_sec;;
  tv.tv_usec = active->tv_usec - now.tv_usec;
  if ( tv.tv_usec < 0 )
  {
   tv.tv_usec += 1000000;
   tv.tv_sec--;
  }
  tvp = &tv;  // get the time difference for timeout
 }
 else
  tvp = NULL;  // no timer
 return ( select( maxp1, re, we, ee, tvp ) );
}
